package com.qiankan.qmsj.fragment;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qiankan.qmsj.R;
import com.qiankan.qmsj.activity.BaseActivity;
import com.qiankan.qmsj.activity.ProductDetailActivity;
import com.qiankan.qmsj.adapter.CommonAdapter;
import com.qiankan.qmsj.entity.Labels;
import com.qiankan.qmsj.entity.Product;
import com.qiankan.qmsj.entity.ProductClassifyEntity;
import com.qiankan.qmsj.entity.Result;
import com.qiankan.qmsj.event.TypeEvent;
import com.qiankan.qmsj.net.APIHub;
import com.qiankan.qmsj.utils.AsyncLoadImage;
import com.qiankan.qmsj.viewHolder.ClassifyAllTypeViewHolder;
import com.qiankan.qmsj.viewHolder.CommonViewHolder;
import com.qiankan.qmsj.viewHolder.ProductViewHolder;
import com.qiankan.qmsj.widget.TipToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/8/16.
 */

public class ClassifyFragment extends BaseFragment {
    @BindView(R.id.emptyView)
    LinearLayout mEmptyView;
    @BindView(R.id.rv_classify)
    RecyclerView mClassify;
    @BindView(R.id.rl_allType)
    RelativeLayout allTypeView;
    @BindView(R.id.rl_synthesize)
    RelativeLayout synthesizeView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefreshLayout;
    private View selectedAllTypeView;
    private View selectedSynthesizeView;
    private PopupWindow allTypePopupWindow;
    private PopupWindow synthesizePopupWindow;
    private String type = "";//类型
    private String minMoney = "";//最小金额
    private String maxMoney = "";//最大金额
    private String minTime = "";//时间
    private String order = "";//排序
    private List<Product> productList;// 产品集合
    private CommonAdapter<Product> productListAdapter;
    private ProductClassifyEntity productClassifyEntity;

    @Override
    public int getContentViewId() {
        return R.layout.classify_fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
        refresh();
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh();
            }
        });
    }

    private void init() {
        allTypeView.setSelected(true);
        synthesizeView.setSelected(false);
        mClassify.setHasFixedSize(true);
        mClassify.setLayoutManager(new LinearLayoutManager(getActivity()));
        mClassify.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        productList = new ArrayList<>();
        productListAdapter = new CommonAdapter<Product>(getActivity(), ProductViewHolder.class, productList, R.layout.product_recommend_item) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, final Product item, int position) {
                ProductViewHolder viewHolder = (ProductViewHolder) holder;
                AsyncLoadImage.loadImage(item.getIcon(), viewHolder.mProductLogo, R.mipmap.ic_launcher);
                viewHolder.mProductName.setText(item.getName());
                viewHolder.mMaxMoney.setText(item.getMaxmoney());
                viewHolder.mAdvertisement.setText(item.getAdvertising());
                viewHolder.mDayRate.setText(String.format("日费率%1$s%%", item.getDayRate()));
                viewHolder.mLoanTime.setText(String.format("贷款期限%1$s-%2$s天", item.getMintime(), item.getMaxtime()));
                viewHolder.mLabelRoot.removeAllViews();
                for (Labels label : item.getLabels()) {
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(10, 0, 0, 0);
                    TextView textView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.text_label_layout, null);
                    textView.setText(label.getName());
                    textView.setLayoutParams(lp);
                    viewHolder.mLabelRoot.addView(textView);
                }
                viewHolder.setOnRecyclerViewListener(new CommonViewHolder.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(View view) {
                        Intent intent = ProductDetailActivity.newIntent(getActivity(), item);
                        startActivity(intent);
                    }
                });
            }
        };
        mClassify.setAdapter(productListAdapter);
    }

    private void refresh() {
        Map<String, String> param = new HashMap<String, String>();
        if (!TextUtils.isEmpty(type)) {
            param.put("type", type);
        }
        if (!TextUtils.isEmpty(minMoney)) {
            param.put("minmoney", minMoney);
        }
        if (!TextUtils.isEmpty(maxMoney)) {
            param.put("maxmoney", maxMoney);
        }
        if (!TextUtils.isEmpty(minTime)) {
            param.put("mintime", minTime);
        }
        if (!TextUtils.isEmpty(order)) {
            param.put("order", order);
        }
        ((BaseActivity) getActivity()).showLoadingDialog();
        if (param.size() > 0) {
            APIHub.getsInstance().getBaseService().getProductForType(param).enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    smartRefreshLayout.finishRefresh();
                    ((BaseActivity) getActivity()).dismissLoadingDialog();
                    Result result = response.body();
                    if (result.getCode().equals("200")) {
                        productClassifyEntity = new Gson().fromJson(result.getData(), ProductClassifyEntity.class);
                        Product firstType = new Product();//手动添加一个全部类型
                        firstType.setName("全部");
                        firstType.setId("");
                        productClassifyEntity.getType().add(0, firstType);
                        productList.clear();
                        productList.addAll(productClassifyEntity.getProducts());
                        if (productList.size() == 0) {
                            mEmptyView.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyView.setVisibility(View.GONE);
                        }
                        productListAdapter.notifyDataSetChanged();
                    } else {
                        TipToast.toast(getActivity(), result.getRemark());
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    smartRefreshLayout.finishRefresh();
                    ((BaseActivity) getActivity()).dismissLoadingDialog();
                    TipToast.toast(getActivity(), "网络连接失败");
                }
            });
        } else {
            APIHub.getsInstance().getBaseService().getProductForType().enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    smartRefreshLayout.finishRefresh();
                    ((BaseActivity) getActivity()).dismissLoadingDialog();
                    Result result = response.body();
                    if (result.getCode().equals("200")) {
                        productClassifyEntity = new Gson().fromJson(result.getData(), ProductClassifyEntity.class);
                        Product firstType = new Product();//手动添加一个全部类型
                        firstType.setName("全部");
                        firstType.setId("");
                        productClassifyEntity.getType().add(0, firstType);
                        productList.clear();
                        productList.addAll(productClassifyEntity.getProducts());
                        if (productList.size() == 0) {
                            mEmptyView.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyView.setVisibility(View.GONE);
                        }
                        productListAdapter.notifyDataSetChanged();
                    } else {
                        TipToast.toast(getActivity(), result.getRemark());
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    smartRefreshLayout.finishRefresh();
                    ((BaseActivity) getActivity()).dismissLoadingDialog();
                    TipToast.toast(getActivity(), "网络连接失败");
                }
            });
        }
    }

    @OnClick(R.id.rl_allType)
    public void onClickAllType(View view) {
        if (allTypePopupWindow == null) {
            View root = getAllTypePopView();
            allTypePopupWindow = new PopupWindow(root, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, true);
            allTypePopupWindow.setBackgroundDrawable(new BitmapDrawable());
            root.findViewById(R.id.all_type_root).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    allTypePopupWindow.dismiss();
                }
            });
        }
        if (Build.VERSION.SDK_INT < 24) {
            allTypePopupWindow.showAsDropDown(view, 0, 2);
        } else {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            allTypePopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, y + view.getHeight());
        }
        allTypeView.setSelected(true);
        synthesizeView.setSelected(false);
    }

    private void initClassifyType(RecyclerView recyclerView) {
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL));
        CommonAdapter<Product> classifyTypeAdapter;
        classifyTypeAdapter = new CommonAdapter<Product>(getActivity(), ClassifyAllTypeViewHolder.class, productClassifyEntity.getType(), R.layout.classify_type_item) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, final Product item, int position) {
                ClassifyAllTypeViewHolder viewHolder = (ClassifyAllTypeViewHolder) holder;
                viewHolder.button.setText(item.getName());
                /*if (item == productClassifyEntity.getType().get(0)) {
                    viewHolder.button.setSelected(true);
                    selectedAllTypeView = viewHolder.button;
                }*/
                viewHolder.setOnRecyclerViewListener(new CommonViewHolder.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(View view) {
                        if (selectedAllTypeView != null) {
                            selectedAllTypeView.setSelected(false);
                        }
                        allTypePopupWindow.dismiss();
                        selectedAllTypeView = view;
                        view.setSelected(true);
                        type = item.getId();
                        refresh();
                    }
                });
            }
        };
        recyclerView.setAdapter(classifyTypeAdapter);
    }

    private View getAllTypePopView() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_all_type, null);
        initClassifyType((RecyclerView) contentView.findViewById(R.id.recyclerView));
        return contentView;
    }

    @OnClick(R.id.rl_synthesize)
    public void onClickSynthesize(View view) {
        if (synthesizePopupWindow == null) {
            View root = getSynthesizePopView();
            synthesizePopupWindow = new PopupWindow(root, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, true);
            synthesizePopupWindow.setBackgroundDrawable(new BitmapDrawable());
            root.findViewById(R.id.pop_synthesize_root).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    synthesizePopupWindow.dismiss();
                }
            });
        }
        if (Build.VERSION.SDK_INT < 24) {
            synthesizePopupWindow.showAsDropDown(view, 0, 2);
        } else {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            synthesizePopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, y + view.getHeight());
        }
        allTypeView.setSelected(false);
        synthesizeView.setSelected(true);
    }

    private View getSynthesizePopView() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_synthesize, null);
        /*selectedSynthesizeView = contentView.findViewById(R.id.btn_cashStage);
        selectedSynthesizeView.setSelected(true);*/
        View.OnClickListener menuItemOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_cashStage:
                        order = "mintime";
                        break;
                    case R.id.btn_lowLimit:
                        order = "minmoney";
                        break;
                    case R.id.btn_largeLimit:
                        order = "maxmoney";
                        break;
                    case R.id.btn_lowRate:
                        order = "maxrate";
                        break;
                    case R.id.btn_highSuccessRate:
                        order = "applynum";
                        break;
                    case R.id.btn_hot:
                        order = "applynum";
                        break;
                }
                if (selectedSynthesizeView != null) {
                    selectedSynthesizeView.setSelected(false);
                }
                synthesizePopupWindow.dismiss();
                selectedSynthesizeView = v;
                v.setSelected(true);
                refresh();
            }
        };
        contentView.findViewById(R.id.btn_cashStage).setOnClickListener(menuItemOnClickListener);
        contentView.findViewById(R.id.btn_lowLimit).setOnClickListener(menuItemOnClickListener);
        contentView.findViewById(R.id.btn_largeLimit).setOnClickListener(menuItemOnClickListener);
        contentView.findViewById(R.id.btn_lowRate).setOnClickListener(menuItemOnClickListener);
        contentView.findViewById(R.id.btn_highSuccessRate).setOnClickListener(menuItemOnClickListener);
        contentView.findViewById(R.id.btn_hot).setOnClickListener(menuItemOnClickListener);
        return contentView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(TypeEvent event) {
        type = TextUtils.isEmpty(event.getType()) ? "" : event.getType();
        minMoney = "";//最小金额
        maxMoney = "";//最大金额
        minTime = "";//时间
        order = "";//排序
        if (selectedAllTypeView != null) {
            selectedAllTypeView.setSelected(false);
        }
        if (selectedSynthesizeView != null) {
            selectedSynthesizeView.setSelected(false);
        }
        refresh();
    }
}
